<template>
  <div class="create-article">
    <h1>{{ isEdit ? '编辑文章' : '创建新文章' }}</h1>
    
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="success" class="success">{{ success }}</div>
    
    <form @submit.prevent="submitForm" class="article-form">
      <div class="form-group">
        <label for="title">标题 <span class="required">*</span></label>
        <input 
          type="text" 
          id="title" 
          v-model="article.title" 
          class="form-control"
          :class="{'error-input': validation.title}"
          required
          placeholder="请输入文章标题"
          @blur="validateTitle"
        >
        <small v-if="validation.title" class="error-text">{{ validation.title }}</small>
      </div>
      
      <div class="form-group">
        <label for="author">作者</label>
        <input 
          type="text" 
          id="author" 
          v-model="article.author" 
          class="form-control"
          placeholder="请输入作者名称"
        >
      </div>
      
      <div class="form-group">
        <label for="tags">标签</label>
        <input 
          type="text" 
          id="tags" 
          v-model="article.tags" 
          class="form-control"
          placeholder="使用逗号分隔多个标签，如: 健康,睡眠,科普"
        >
        <small class="form-text">多个标签使用英文逗号(,)分隔</small>
      </div>
      
      <div class="form-group">
        <label for="cover">封面图片</label>
        <div class="cover-upload">
          <div class="preview" v-if="article.coverImage">
            <img :src="getImageUrl(article.coverImage)" alt="封面预览">
            <button type="button" class="btn btn-danger btn-sm" @click="removeCover">
              移除封面
            </button>
          </div>
          <div class="upload-control" v-if="!article.coverImage">
            <input 
              type="file" 
              id="cover" 
              @change="uploadCover" 
              accept="image/jpeg,image/png,image/gif"
            >
            <label for="cover" class="upload-label">选择封面图片</label>
          </div>
        </div>
        <small class="form-text">建议尺寸: 1200 x 675 像素，支持 JPG、PNG 和 GIF 格式，大小不超过5MB</small>
      </div>
      
      <div class="form-group">
        <label for="content">正文内容 <span class="required">*</span></label>
        <div class="editor-wrapper">
          <textarea 
            id="content" 
            v-model="article.content" 
            class="form-control"
            :class="{'error-input': validation.content}"
            required
            rows="15"
            placeholder="在此输入文章正文（支持Markdown格式）"
            @blur="validateContent"
          ></textarea>
          <small v-if="validation.content" class="error-text">{{ validation.content }}</small>
          <div class="markdown-tips">
            <p>Markdown 格式提示:</p>
            <ul>
              <li># 标题一</li>
              <li>## 标题二</li>
              <li>**粗体文本**</li>
              <li>*斜体文本*</li>
              <li>[链接文本](https://example.com)</li>
              <li>![图片描述](图片URL)</li>
            </ul>
          </div>
        </div>
      </div>
      
      <div v-if="isEdit && article.status === 'published'" class="article-status">
        <div class="status-badge published">已发布状态</div>
        <small>更新文章将保持已发布状态</small>
      </div>
      
      <div v-if="isEdit && article.status === 'draft'" class="article-status">
        <div class="status-badge draft">草稿状态</div>
        <small>点击「立即发布」可将草稿改为发布状态</small>
      </div>
      
      <div class="form-actions">
        <button 
          type="button" 
          class="btn btn-secondary" 
          @click="saveDraft"
          :disabled="saving || publishing"
        >
          {{ saving ? '正在保存...' : '保存草稿' }}
        </button>
        <button 
          type="submit" 
          class="btn btn-primary"
          :disabled="saving || publishing"
        >
          {{ publishing ? '正在发布...' : '立即发布' }}
        </button>
        <button 
          type="button" 
          class="btn btn-outline" 
          @click="goBack"
        >
          取消
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

export default defineComponent({
  setup() {
    const route = useRoute();
    const router = useRouter();
    
    const articleId = ref(route.params.id);
    const isEdit = ref(!!articleId.value);
    
    const article = reactive({
      id: null,
      title: '',
      content: '',
      author: '',
      coverImage: '',
      tags: '',
      status: 'draft',
      viewCount: 0
    });
    
    const validation = reactive({
      title: '',
      content: ''
    });
    
    const loading = ref(false);
    const error = ref('');
    const success = ref('');
    const saving = ref(false);
    const publishing = ref(false);
    
    const validateTitle = () => {
      validation.title = '';
      
      if (!article.title) {
        validation.title = '标题不能为空';
        return false;
      }
      
      if (article.title.length > 100) {
        validation.title = '标题不能超过100个字符';
        return false;
      }
      
      return true;
    };
    
    const validateContent = () => {
      validation.content = '';
      
      if (!article.content) {
        validation.content = '内容不能为空';
        return false;
      }
      
      return true;
    };
    
    const validateForm = () => {
      const titleValid = validateTitle();
      const contentValid = validateContent();
      
      return titleValid && contentValid;
    };
    
    const getImageUrl = (imagePath) => {
      if (!imagePath) return '';
      // 如果路径已经是完整URL，直接返回
      if (imagePath.startsWith('http')) return imagePath;
      // 如果路径是相对路径，加上后端服务器地址
      if (imagePath.startsWith('/')) {
        return `http://localhost:9001${imagePath}`;
      }
      return `http://localhost:9001/${imagePath}`;
    };
    
    const fetchArticle = async () => {
      if (!articleId.value) return;
      
      loading.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/article/detail/${articleId.value}`);
        if (!response.ok) {
          throw new Error('获取文章详情失败');
        }
        
        const data = await response.json();
        
        // 填充表单
        article.id = data.id;
        article.title = data.title;
        article.content = data.content;
        article.author = data.author || '';
        article.coverImage = data.coverImage || '';
        article.tags = data.tags || '';
        article.status = data.status;
        article.viewCount = data.viewCount || 0;
      } catch (err) {
        console.error('获取文章详情时出错:', err);
        error.value = '获取文章失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    const uploadCover = async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件类型
      if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
        error.value = '只支持JPG、PNG和GIF格式的图片';
        return;
      }
      
      // 检查文件大小 (限制为5MB)
      if (file.size > 5 * 1024 * 1024) {
        error.value = '图片大小不能超过5MB';
        return;
      }
      
      const formData = new FormData();
      formData.append('file', file);
      
      loading.value = true;
      error.value = '';
      
      try {
        const response = await fetch('http://localhost:9001/api/article/upload-cover', {
          method: 'POST',
          body: formData
        });
        
        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(errorText || '上传封面失败');
        }
        
        let imageUrl = await response.text();
        // 上传图片后回显
        if (imageUrl && !/^https?:\/\//.test(imageUrl)) {
          if (!imageUrl.startsWith('/image')) {
            imageUrl = '/image' + imageUrl.replace(/^\/static/, '');
          }
        }
        article.coverImage = imageUrl;
      } catch (err) {
        console.error('上传封面图片时出错:', err);
        error.value = '上传封面失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    const removeCover = () => {
      article.coverImage = '';
    };
    
    const saveDraft = async () => {
      if (!validateTitle()) {
        return;
      }
      
      saving.value = true;
      error.value = '';
      success.value = '';
      
      try {
        const url = isEdit.value 
          ? `http://localhost:9001/api/article/update/${article.id}`
          : 'http://localhost:9001/api/article/saveDraft';
        
        const method = isEdit.value ? 'PUT' : 'POST';
        
        // 设置为草稿状态
        article.status = 'draft';
        
        const response = await fetch(url, {
          method: method,
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(article)
        });
        
        if (!response.ok) {
          throw new Error('保存草稿失败');
        }
        
        const data = await response.json();
        
        if (!isEdit.value) {
          article.id = data.id;
          isEdit.value = true;
          articleId.value = data.id;
          // 更新URL，但不重新加载页面
          window.history.pushState(
            {}, 
            '', 
            `/article/edit/${data.id}`
          );
        }
        
        success.value = '草稿已保存';
        setTimeout(() => {
          success.value = '';
        }, 3000);
      } catch (err) {
        console.error('保存草稿时出错:', err);
        error.value = '保存草稿失败: ' + err.message;
      } finally {
        saving.value = false;
      }
    };
    
    const submitForm = async () => {
      if (!validateForm()) {
        return;
      }
      
      publishing.value = true;
      error.value = '';
      success.value = '';
      
      try {
        const url = isEdit.value 
          ? `http://localhost:9001/api/article/update/${article.id}`
          : 'http://localhost:9001/api/article/create';
        
        const method = isEdit.value ? 'PUT' : 'POST';
        
        // 设置为发布状态
        article.status = 'published';
        
        const response = await fetch(url, {
          method: method,
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(article)
        });
        
        if (!response.ok) {
          throw new Error('发布文章失败');
        }
        
        success.value = '文章已成功发布';
        setTimeout(() => {
          // 发布成功后跳转到文章列表页
          router.push('/article/list');
        }, 1500);
      } catch (err) {
        console.error('发布文章时出错:', err);
        error.value = '发布文章失败: ' + err.message;
      } finally {
        publishing.value = false;
      }
    };
    
    const goBack = () => {
      router.go(-1);
    };
    
    onMounted(() => {
      if (isEdit.value) {
        fetchArticle();
      }
    });
    
    return {
      article,
      loading,
      error,
      success,
      saving,
      publishing,
      isEdit,
      validation,
      getImageUrl,
      uploadCover,
      removeCover,
      saveDraft,
      submitForm,
      validateTitle,
      validateContent,
      goBack
    };
  }
});
</script>

<style scoped>
.create-article {
  max-width: 960px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.article-form {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.required {
  color: #f44336;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-control.error-input {
  border-color: #f44336;
}

.error-text {
  color: #f44336;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

textarea.form-control {
  min-height: 300px;
  resize: vertical;
  font-family: monospace;
}

.cover-upload {
  margin-top: 10px;
}

.preview {
  display: inline-block;
  position: relative;
  margin-bottom: 10px;
}

.preview img {
  max-width: 200px;
  max-height: 150px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.preview .btn {
  position: absolute;
  top: 5px;
  right: 5px;
  padding: 2px 5px;
  font-size: 12px;
}

.upload-control {
  position: relative;
  display: inline-block;
}

.upload-control input[type="file"] {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
}

.upload-label {
  display: inline-block;
  padding: 10px 15px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-label:hover {
  background-color: #e0e0e0;
}

.form-text {
  display: block;
  margin-top: 5px;
  color: #666;
  font-size: 12px;
}

.editor-wrapper {
  position: relative;
}

.markdown-tips {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
  font-size: 13px;
}

.markdown-tips p {
  margin: 0 0 5px;
  font-weight: bold;
}

.markdown-tips ul {
  margin: 0;
  padding-left: 20px;
}

.article-status {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.status-badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 16px;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.status-badge.published {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-badge.draft {
  background-color: #fff3e0;
  color: #e65100;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-secondary {
  background-color: #2196F3;
  color: white;
}

.btn-outline {
  background-color: transparent;
  border: 1px solid #ddd;
  color: #333;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 12px;
}

.loading, .error, .success {
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.loading {
  background-color: #f9f9f9;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}

.success {
  background-color: #e8f5e9;
  color: #2e7d32;
}

@media (max-width: 768px) {
  .form-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
}
</style> 